﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TRPOP.CMS.RegAssembly;
using System.Text.RegularExpressions;
using TRPOP.Common;
using System.CodeDom.Compiler;
using System.IO;
namespace TRPOP.CMS.Template.GenerateCS
{
    /// <summary>
    ///  生成Csharp代码时 通用的代码
    /// </summary>
    public class CommonCodeForCSFile
    {

        /// <summary>
        /// 读取模板内容后，基本操作
        /// </summary>
        /// <param name="strBuild"></param>
        /// <param name="oTemplateDllPageInfo"></param>
        public static void BaseOperStart(StringBuilder strBuild, TemplateDllPageInfo oTemplateDllPageInfo)
        {
            //using dlls
            strBuild.Append(BaseOperUsing());

            //生成的页面声明部分
            strBuild.Append(BaseOperGetGlobalNote(oTemplateDllPageInfo));

            strBuild.Append(
string.Format(
@"
namespace TRPOP.CMS.TemplateDlls
{{      
    public class TpDlls{0} : ItemplateControl
    {{      

{1}
{2}
        //根据传递的模板实体类型，组合html代码
        public TemplateDllPageInfo Analysis(TemplateDllPageInfo oParamInfo)
        {{      
            
{3}             
",
StringExtension.GetGuidStrWithNumberAndChar(),// 类，均是以TpDlls开头，然后后面加上guid(去掉-) 并继承 ItemplateControl 类
BaseOperGetGlobalVariable("\t\t"),          //全局变量
BaseOperFuncForCS("\t\t"),                  //公共方法
BaseOperGetAnalysisInitCode("\t\t\t")       //Analysis的init代码
));
            #region 原来的代码
            /*            
            //命名空间
            strBuild.AppendLine("namespace TRPOP.CMS.TemplateDlls");
            strBuild.AppendLine("{");

            //类，均是以TpDlls开头，然后后面加上guid(去掉-) 并继承 ItemplateControl 类
            strBuild.AppendLine("\tpublic class " + "TpDlls" + Guid.NewGuid().ToString().Replace("-", "") + " : ItemplateControl");
            strBuild.AppendLine("\t{");

             

            //全局变量
            strBuild.Append(BaseOperGetGlobalVariable("\t\t"));

            //公共方法
            strBuild.AppendLine();
            strBuild.Append(BaseOperFuncForCS("\t\t"));

            //生成html页面的方法
            strBuild.AppendLine();
            strBuild.AppendLine("\t\t//根据传递的模板实体类型，组合html代码");
            strBuild.AppendLine("\t\tpublic TemplateDllPageInfo Analysis(TemplateDllPageInfo oParamInfo)");
            strBuild.AppendLine("\t\t{");
            //Analysis 的init代码
            strBuild.Append(BaseOperGetAnalysisInitCode("\t\t\t"));
            //ConvertTags类 将根据不同的html模板进行不同的标签转换
            */
            #endregion
        }

        /// <summary>
        /// 最后的处理
        /// </summary>
        /// <param name="strBuild"></param>
        public static void BaseOperEnd(StringBuilder strBuild, TemplateDllPageInfo oTemplateDllPageInfo)
        {
            strBuild.Append(
@"
            
            #endregion

            //根据不同的页面类型做不同的预处理
            DateTime oEndOper_start = DateTime.Now;
            CommonMethord.PageOper_end(oTemplatePageInfo, m_IDAL);
            DateTime oEndOper_end = DateTime.Now;
            oTemplatePageInfo.intEndExecuteDataTimeSpan = Convert.ToInt32(oEndOper_end.Subtract(oEndOper_start).TotalMilliseconds);

            //计时结束
            DateTime oTimeEnd = DateTime.Now;
            oParamInfo.intTotalTimeSpan = Convert.ToInt32(oTimeEnd.Subtract(oTimeStart).TotalMilliseconds);

            return oTemplatePageInfo;

        }       
    }       
}       
");
            #region 原来的代码
            /*
            strBuild.AppendLine();
            strBuild.AppendLine("\t\t\treturn oTemplatePageInfo;");//public TemplateDllPageInfo Analysis end
            strBuild.AppendLine();
            strBuild.AppendLine("\t\t}");//public TemplateDllPageInfo Analysis
            strBuild.AppendLine();

            strBuild.AppendLine("\t}");//class
            strBuild.AppendLine("}");//namespace
            */
            #endregion
        }

        /// <summary>
        /// using
        /// </summary>
        /// <returns></returns>
        public static string BaseOperUsing()
        {
            return strUsing;
        }
        /// <summary>
        /// 生成的cs文件的总体的信息提示
        /// </summary>
        /// <param name="strSpace"></param>
        /// <param name="oTemplateDllPageInfo"></param>
        /// <returns></returns>
        public static string BaseOperGetGlobalNote(TemplateDllPageInfo oTemplateDllPageInfo)
        {
            return string.Format(strGlobalNote, DateTime.Now.ToString(), oTemplateDllPageInfo.strTemplateFilePath);
        }
        /// <summary>
        /// 获取全局变量的cSharp函数
        /// </summary>
        /// <param name="strSpace"></param>
        /// <returns></returns>
        public static string BaseOperGetGlobalVariable(string strSpace)
        {
            return AppendBeforbySpaces(strSpace, string.Format(strGlobalVariable,"\""));
        }
        /// <summary>
        /// Analysis 的初始化代码
        /// </summary>
        /// <param name="strSapce"></param>
        /// <returns></returns>
        public static string BaseOperGetAnalysisInitCode(string strSapce)
        {
            return AppendBeforbySpaces(strSapce, strAnalysisInitCode);
        }
        /// <summary>
        /// CS文件里的方法
        /// </summary>
        /// <param name="strSpace"></param>
        /// <returns></returns>
        public static string BaseOperFuncForCS(string strSpace)
        {
            return AppendBeforbySpaces(strSpace, strBaseFunc);
        }

        #region 私有方法
        /// <summary>
        /// 在每行数据前添加指定的字符串
        /// </summary>
        /// <param name="strSpace"></param>
        /// <param name="strSource"></param>
        /// <returns></returns>
        private static string AppendBeforbySpaces(string strSpace, string strSource)
        {
            StringBuilder strBuild = new StringBuilder(strSource.Length);
            string[] Separators = new string[] { Environment.NewLine };
            string[] aryString = strSource.Split(Separators, StringSplitOptions.None);
            foreach (string LineString in aryString)
            {
                strBuild.AppendLine(strSpace + LineString);
            }
            return strBuild.ToString();
        }
        #endregion

        #region 私有属性
        /// <summary>
        /// using
        /// </summary>
        private const string strUsing =
@"using System;
using System.Data;
using System.Collections.Generic;
using TRPOP.Common;
using TRPOP.CMS.Plugin;
using TRPOP.CMS.Template.GenerateCS;
using System.Collections;
";
        /// <summary>
        /// 注释
        /// </summary>
        private const string strGlobalNote =
@"
/*
    本页面代码由YorkCMS模板引擎生成于 {0}
    模板文件物理路径：  {1}
    说明： 
        1 【代码的注释部分】关于行信息的提示，可能与实际的模板文件的行信息不符，是因为读取模板文件后，对空行做了去除处理，对include的文件做了二次加载处理，所以，这里的行信息提示进攻参考，不做标准验证
*/
";

        /// <summary>
        /// 全局变量
        /// </summary>
        private const string strGlobalVariable =
@"#region 全局变量

IDAL m_IDAL = ITemplateAccess.GetIDalInstance();//全局数据操作接口
IFunc m_IFunc = ITemplateAccess.GetIFuncInstance();//全局函数操作接口

Dictionary<string, DataTable> oDictionaryTable = new Dictionary<string, DataTable>();//全局公共Table池
Dictionary<string, DataRow> oDictionaryRow = new Dictionary<string, DataRow>();//全局公共Row池
Dictionary<string, object> oDictionaryObj = new Dictionary<string, object>();//全局公共object池

const string strCurrenContent = {0}CurrenContent{0};//当前信息的内容所对应的oDictionaryRow的标识key
const string strNodeInfo = {0}NodeInfo{0};//当前信息的结点info所对应的oDictionaryRow的标识key
const string strIndexID = {0}IndexID{0};//当前内容所对应的oDictionaryObj的标识key
const string strNodeID = {0}NodeID{0};//当前结点所对应的oDictionaryObj的标识key

TemplateDllPageInfo oTemplatePageInfo = new TemplateDllPageInfo();//全局的模板实体

#endregion";
        /// <summary>
        /// 公共方法
        /// </summary>
        private const string strBaseFunc =
@"#region 公共方法

/// <summary>
/// 获取变量值的方法
/// </summary>
public string GetTagValue(string strDataSet, string strIndex, string strVar)
{
    return CommonMethord.GetTagValue(strDataSet, strIndex, strVar, oDictionaryTable, oDictionaryRow, oDictionaryObj, oTemplatePageInfo, strCurrenContent, m_IDAL);
}

/// <summary>
/// 设定某一变量
/// </summary>
public void SaveVar(string strName, object objValue)
{
    CommonMethord.SaveVar(strName, objValue, oTemplatePageInfo, oDictionaryObj);
}

/// <summary>
///  保存一行数据到 DataRow 库中
/// </summary>
public void SaveRow(string strName, DataRow oDataRow)
{
    CommonMethord.SaveRow(strName, oDataRow, oDictionaryRow);
}

/// <summary>
/// 保存table到 DataTable 库中 
/// </summary>
public void SaveTable(string strName, DataTable oTable)
{
    CommonMethord.SaveTable(strName, oTable, oDictionaryTable);
}

/// <summary>
/// 根据CMS标签的Attributes将数据保存至公共变量库中
/// </summary>
public void SaveCMSTagData(Dictionary<string, string> oAttributes)
{
    CommonMethord.SaveCMSTagData(oAttributes, oDictionaryTable, oDictionaryRow, oDictionaryObj, oTemplatePageInfo);
}

/// <summary>
/// 执行函数，返回string
/// </summary>
public string ExeCuteFunc(string strFuncName, ArrayList olistParams)
{
    bool isSuccess = false;
    object obj = IFuncControl.ExecuteFunctionForDll(strFuncName, olistParams, ref isSuccess, m_IFunc);
    return obj.ToString();
}

/// <summary>
/// 替换字符串里特殊的字符串
/// </summary>
public string ConvertSpecialChar(string strSource)
{
    return strSource;// CommonMethord.ConvertSpecialChar(strSource);
}

/// <summary>
/// 根据key获取datatable
/// </summary>
public DataTable getDT(string strKey)
{
    DateTime _start = DateTime.Now;
    DataTable oReturn =  CommonMethord.GetDtByKeyName(strKey, oDictionaryTable, oDictionaryRow);
    DateTime _end = DateTime.Now;
    oTemplatePageInfo.intDataTimeSpan += Convert.ToInt32(_end.Subtract(_start).TotalMilliseconds);
    return oReturn;
}

/// <summary>
/// 检测是否为空
/// </summary>
public bool empty(string strSource)
{
    return strSource.Trim().Length <= 0;
}

#endregion";
        /// <summary>
        /// Analysis 函数里  初始化的代码
        /// </summary>
        private static string strAnalysisInitCode =
@"
//开始计时
DateTime oTimeStart = DateTime.Now;
oParamInfo.intTotalTimeSpan = 0;
oParamInfo.intDataTimeSpan = 0;

#region 初始化基本的数据

//将与设定的变量添加到当前集合里
CommonMethord.InitPageVar(oParamInfo, oDictionaryObj);

//将传递的实体初始化到全局实体里
oTemplatePageInfo = oParamInfo;
if (oTemplatePageInfo.intCurrentContentID > 0 && oTemplatePageInfo.oContentInfoRow == null)
{
    DataTable oContentInfoDataTable = m_IDAL.GetContentWithImgResource(oTemplatePageInfo.intCurrentContentID.ToString());
    if (oContentInfoDataTable != null && oContentInfoDataTable.Rows.Count > 0)
    {
        oTemplatePageInfo.oContentInfoRow = m_IDAL.GetContentWithImgResource(oTemplatePageInfo.intCurrentContentID.ToString()).Rows[0];
    }
    else
    {
        oTemplatePageInfo.oContentInfoRow = null;
    }
}
if (oTemplatePageInfo.intCurrentNodeID > 0 && oTemplatePageInfo.oNodeInfoRow == null)
{
    oTemplatePageInfo.oNodeInfoRow = m_IDAL.GetNodeInfo(false, oTemplatePageInfo.intCurrentNodeID.ToString(), false, string.Empty) as DataRow;
}

//添加当前结点信息、内容信息到全局变量库里
SaveRow(strNodeInfo, oTemplatePageInfo.oNodeInfoRow);//oDictionaryRow.Add(strNodeInfo, oTemplatePageInfo.oNodeInfoRow);
SaveRow(strCurrenContent, oTemplatePageInfo.oContentInfoRow);//oDictionaryRow.Add(strCurrenContent, oTemplatePageInfo.oContentInfoRow);

//添加当前结点id、信息id到全局变量库里
SaveVar(strIndexID, oTemplatePageInfo.intCurrentContentID);//oDictionaryObj.Add(strIndexID, oTemplatePageInfo.intCurrentContentID);
SaveVar(strNodeID, oTemplatePageInfo.intCurrentNodeID);//oDictionaryObj.Add(strNodeID, oTemplatePageInfo.intCurrentNodeID);
" +
string.Format(@"

//保存页面全局变量
SaveRow({0}PageInfo{0}, CommonMethord.InitPageInfo(oTemplatePageInfo));

//根据不同的页面类型做不同的预处理
DateTime oPreOper_start = DateTime.Now;
CommonMethord.PageOper_pre(oTemplatePageInfo, m_IDAL);
DateTime oPreOper_end = DateTime.Now;
oTemplatePageInfo.intPreExecuteDataTimeSpan = Convert.ToInt32(oPreOper_end.Subtract(oPreOper_start).TotalMilliseconds);

", "\"")
+@"#endregion

#region 临时变量
            
ArrayList olistParams = new ArrayList();//函数的参数
            
bool isSuccess = true;//是否正确执行
            
Dictionary<string, string> oAttributes = new Dictionary<string, string>();//CMS标签的参数

//DataTable oDataTabletemp = null;//临时DataTable
//DataRow oDataRowtemp = null;//临时DataRow

#endregion

#region 处理模板标签 
";
        #endregion
    }
}